/*
 *  Copyright (C) 2011 Jaime Pavlich-Mariscal
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


package cl.ucn.disc.biblio.refcluster;

import java.io.File;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.GroupLayout;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 *
 * @author Jaime Pavlich
 */
public class ReferenceClustererWindow extends javax.swing.JFrame {

	private static final long serialVersionUID = -744476234820635268L;
	private JFileChooser fileChooser = new JFileChooser();
    private JFileChooser folderChooser = new JFileChooser();
//    private File wosDBFolder;
//    private File clusterFile;
//    private File newDBFolder;

    /** Creates new form ReferenceMatcherJFrame */
    public ReferenceClustererWindow() {
        try {
        	
            initComponents();
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ReferenceClustererWindow.class.getName()).error("", ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(ReferenceClustererWindow.class.getName()).error("",  ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(ReferenceClustererWindow.class.getName()).error("",  ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(ReferenceClustererWindow.class.getName()).error("",  ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtFieldBiblioDBFolder = new javax.swing.JTextField();
        jButtonBrowseDBFolder = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtFieldClusterFilename = new javax.swing.JTextField();
        jButtonBrowseClusterFile = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtFieldNewDBFolder = new javax.swing.JTextField();
        jButtonBrowseNewDBFolder = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButtonGenerateClusterFile = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButtonGenerateNewDB = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Reference Clusterer");

        jLabel1.setText("Bibliographic database folder:  ");

        txtFieldBiblioDBFolder.setText("/RefClustererData/DB");
        txtFieldBiblioDBFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldBiblioDBFolderActionPerformed(evt);
            }
        });

        jButtonBrowseDBFolder.setText("Browse");
        jButtonBrowseDBFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseDBFolderActionPerformed(evt);
            }
        });

        jLabel2.setText("Cluster file:");

        txtFieldClusterFilename.setText("/RefClustererData/reference_clusters.txt");

        jButtonBrowseClusterFile.setText("Browse");
        jButtonBrowseClusterFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseClusterFileActionPerformed(evt);
            }
        });

        jLabel3.setText("New bibliographic database folder:");

        txtFieldNewDBFolder.setText("/RefClustererData/NewDB");

        jButtonBrowseNewDBFolder.setText("Browse");
        jButtonBrowseNewDBFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseNewDBFolderActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setText("Step 1: Select folder of where the bibliographic database is stored");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setText("Step 2: Specify the cluster file name");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel6.setText("Step 3: Generate the cluster file");

        jButtonGenerateClusterFile.setText("Generate cluster file");
        jButtonGenerateClusterFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGenerateClusterFileActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel7.setText("Step 5: Select folder for the new database");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel8.setText("Step 6: Generate the new database");

        jButtonGenerateNewDB.setText("Generate new database");
        jButtonGenerateNewDB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGenerateNewDBActionPerformed(evt);
            }
        });
        
        JLabel lblWarningThisWill = new JLabel("WARNING: This will delete all of the files in the new database folder!");
        lblWarningThisWill.setForeground(Color.RED);
        lblWarningThisWill.setFont(new Font("Tahoma", Font.BOLD, 11));
        
        JLabel lblStepSelect = new JLabel("Step 4: Specify author disambiguation");
        lblStepSelect.setFont(new Font("Tahoma", Font.BOLD, 11));
        
        lblAuthorClusterFile = new JLabel();
        lblAuthorClusterFile.setText("If so, then select author cluster file:");
        lblAuthorClusterFile.setEnabled(false);
        
        txtAuthorClusterFile = new JTextField();
        txtAuthorClusterFile.setText("/RefClustererData/author_clusters.txt");
        txtAuthorClusterFile.setEnabled(false);
        
        buttonBrowseAuthorClusterFile = new JButton();
        buttonBrowseAuthorClusterFile.setText("Browse");
        buttonBrowseAuthorClusterFile.setEnabled(false);
        
        cbDisambiguateAuthors = new JCheckBox("Disambiguate authors?");
        cbDisambiguateAuthors.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		lblAuthorClusterFile.setEnabled(cbDisambiguateAuthors.isSelected());
        		txtAuthorClusterFile.setEnabled(cbDisambiguateAuthors.isSelected());
        		buttonBrowseAuthorClusterFile.setEnabled(cbDisambiguateAuthors.isSelected());
        	}
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addComponent(jLabel4)
        				.addComponent(jButtonGenerateClusterFile)
        				.addComponent(jLabel6)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(txtFieldClusterFilename, GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
        					.addPreferredGap(ComponentPlacement.UNRELATED)
        					.addComponent(jButtonBrowseClusterFile))
        				.addGroup(layout.createSequentialGroup()
        					.addGroup(layout.createParallelGroup(Alignment.LEADING)
        						.addComponent(jLabel5)
        						.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 214, GroupLayout.PREFERRED_SIZE))
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(txtFieldBiblioDBFolder, GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
        					.addPreferredGap(ComponentPlacement.UNRELATED)
        					.addComponent(jButtonBrowseDBFolder))
        				.addComponent(lblStepSelect)
        				.addComponent(jButtonGenerateNewDB)
        				.addComponent(lblWarningThisWill)
        				.addComponent(jLabel8)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 217, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(txtFieldNewDBFolder, GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
        					.addGap(10)
        					.addComponent(jButtonBrowseNewDBFolder))
        				.addComponent(jLabel7)
        				.addComponent(cbDisambiguateAuthors)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(lblAuthorClusterFile, GroupLayout.PREFERRED_SIZE, 217, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(txtAuthorClusterFile, GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(buttonBrowseAuthorClusterFile, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)))
        			.addContainerGap())
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(jLabel4)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(txtFieldBiblioDBFolder, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jLabel1)
        				.addComponent(jButtonBrowseDBFolder))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(jLabel5)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel2)
        				.addComponent(txtFieldClusterFilename, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jButtonBrowseClusterFile))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(jLabel6)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jButtonGenerateClusterFile)
        			.addGap(18)
        			.addComponent(lblStepSelect)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(cbDisambiguateAuthors)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(2)
        					.addComponent(lblAuthorClusterFile))
        				.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        					.addComponent(txtAuthorClusterFile, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        					.addComponent(buttonBrowseAuthorClusterFile)))
        			.addPreferredGap(ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
        			.addComponent(jLabel7)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel3)
        				.addComponent(txtFieldNewDBFolder, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jButtonBrowseNewDBFolder))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(jLabel8)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(lblWarningThisWill)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jButtonGenerateNewDB)
        			.addGap(43))
        );
        getContentPane().setLayout(layout);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-668)/2, (screenSize.height-368)/2, 668, 466);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonBrowseDBFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseDBFolderActionPerformed
        int returnVal = folderChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File wosDBFolder = folderChooser.getSelectedFile();
            txtFieldBiblioDBFolder.setText(wosDBFolder.getAbsolutePath());
        }
    }//GEN-LAST:event_jButtonBrowseDBFolderActionPerformed

    private void jButtonGenerateClusterFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGenerateClusterFileActionPerformed
        try {
            File wosDBFolder = new File(txtFieldBiblioDBFolder.getText());
            File clusterFile = new File(txtFieldClusterFilename.getText());
            ReferenceClusterer rc = new ReferenceClusterer();
            if (wosDBFolder != null && clusterFile != null) {
                rc.createClusterFileFromWoSDB(wosDBFolder, clusterFile);
            } else {
                JOptionPane.showMessageDialog(this, "Select Bibliographic database and cluster file", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Throwable t) {
            JOptionPane.showMessageDialog(this, t.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            t.printStackTrace();
        }
    }//GEN-LAST:event_jButtonGenerateClusterFileActionPerformed

    private void jButtonBrowseClusterFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseClusterFileActionPerformed
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File clusterFile = fileChooser.getSelectedFile();
            txtFieldClusterFilename.setText(clusterFile.getAbsolutePath());
        }
    }//GEN-LAST:event_jButtonBrowseClusterFileActionPerformed

    private void jButtonGenerateNewDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGenerateNewDBActionPerformed
        ReferenceManager rm = new ReferenceManager();
        try {
            File wosDBFolder = new File(txtFieldBiblioDBFolder.getText());
            File clusterFile = new File(txtFieldClusterFilename.getText());
            File newDBFolder = new File(txtFieldNewDBFolder.getText());
            File authorClusterFile = null;
            if (cbDisambiguateAuthors.isSelected()) {
            	authorClusterFile = new File(txtAuthorClusterFile.getText());
            }
            rm.replaceRefsOfFolder(wosDBFolder, newDBFolder, clusterFile, authorClusterFile);
            
            

        } catch (Throwable t) {
            JOptionPane.showMessageDialog(this, t.toString(), "Error", JOptionPane.ERROR_MESSAGE);
//            t.printStackTrace();
        }
    }//GEN-LAST:event_jButtonGenerateNewDBActionPerformed

    private void jButtonBrowseNewDBFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseNewDBFolderActionPerformed
        int returnVal = folderChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File newDBFolder = folderChooser.getSelectedFile();
            txtFieldNewDBFolder.setText(newDBFolder.getAbsolutePath());
        }
    }//GEN-LAST:event_jButtonBrowseNewDBFolderActionPerformed

    private void jTextFieldBiblioDBFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldBiblioDBFolderActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldBiblioDBFolderActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ReferenceClustererWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBrowseClusterFile;
    private javax.swing.JButton jButtonBrowseDBFolder;
    private javax.swing.JButton jButtonBrowseNewDBFolder;
    private javax.swing.JButton jButtonGenerateClusterFile;
    private javax.swing.JButton jButtonGenerateNewDB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField txtFieldBiblioDBFolder;
    private javax.swing.JTextField txtFieldClusterFilename;
    private javax.swing.JTextField txtFieldNewDBFolder;
    private JLabel lblAuthorClusterFile;
    private JTextField txtAuthorClusterFile;
    private JButton buttonBrowseAuthorClusterFile;
	private JCheckBox cbDisambiguateAuthors;
}
